package com.fly.office.word.util;

import org.apache.commons.lang3.StringUtils;
import org.apache.poi.openxml4j.exceptions.InvalidFormatException;
import org.apache.poi.xwpf.usermodel.XWPFDocument;
import org.apache.poi.xwpf.usermodel.XWPFParagraph;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.FileNotFoundException;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * 文本处理
 */
public class TextUtil {

    private static Logger logger = LoggerFactory.getLogger(TextUtil.class);

    /**
     * 拿到文本标签的正则表达式
     */
    private static final String pattern = "\\{\\{+[a-zA-Z0-9]+\\}\\}";

    /**
     * 处理段落文字
     *
     * @param doc
     * @throws InvalidFormatException
     * @throws FileNotFoundException
     * @throws IOException
     */
    public static void doParagraphs(XWPFDocument doc,Map<String, String> textMap) throws Exception {

        /**----------------------------处理段落------------------------------------**/
        List<XWPFParagraph> paragraphList = doc.getParagraphs();
        if (paragraphList != null && paragraphList.size() > 0) {
            for (XWPFParagraph paragraph : paragraphList) {
                // 段落文字
                String ptext = paragraph.getText();

                logger.info("段落文本：{}",ptext);

                if (StringUtils.isNotEmpty(ptext)) {
                    // 段落里面的标签
                    List<String> resList = resolver(ptext);
                    for (String flag : resList) {
                        String key = flag.replace("{{", "").replace("}}", "");
//                        String key = flag.replaceAll("\\{\\{", "").replaceAll("}}", "");
                        String label = textMap.get(key);
                        if (StringUtils.isNotEmpty(label)) {
                            // 替换段落文字
                            ptext = ptext.replace(flag, label);
                        }
                    }
                }

                // 清除段落所有的run，解决run文字分段问题
                for (int i = 0; i < paragraph.getRuns().size(); i++) {
                    paragraph.removeRun(i);
                }
                // 主动添加一个run并设置文本内容
                paragraph.insertNewRun(0).setText(ptext);

            }
        }
    }


    /**
     * 解析段落，获取里面的标签
     */
    public static List<String> resolver(String line) {
        List<String> resList = new ArrayList<String>();
        try {
            //编译正则表达式
            Pattern patten = Pattern.compile(pattern);
            // 指定要匹配的字符串
            Matcher matcher = patten.matcher(line);
            //此处find（）每次被调用后，会偏移到下一个匹配
            while (matcher.find()) {
                String flag = matcher.group();
                resList.add(flag);
            }
        } catch (Exception e) {
            logger.error("异常：{}",e);
        }
        return resList;
    }


}
